<template>
  <div class="container-app">
    <div class="btn-group">
      <el-button v-if="hasAdd" size="small" type="success" @click="addLine"><i class="el-icon-plus"></i>{{addTitle}}</el-button>
      <el-button v-if="hasDel" size="small" type="danger" @click="removeLine"><i class="el-icon-delete"></i>{{delTitle}}</el-button>
      <el-button v-if="hasUpdate" size="small" type="primary" @click="changeLine"><i class="el-icon-edit-outline"></i>{{updateTitle}}</el-button>
      <span class="right-search">
        <el-input @change="findLine" v-model="deptSerData" size="small" placeholder="输入关键字搜索" style="width:300px;">
          <el-button @click="findLine" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </span>
    </div>
    <tree-table @selectChange="choice" :data="deptData" :columns="columns" border></tree-table>

   <!--对话界面-->
    <el-dialog :title="title" :visible.sync="deptVisible" width="30%" :before-close="handleClose" :close-on-click-modal='false'>
      <el-form :model="deptForm" :rules="rules" ref="deptForm" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input :disabled="isUpdate" size="small" v-model="deptForm.name"></el-input>
        </el-form-item>
        <el-form-item label="部门描述" prop="remark">
          <el-input type="textarea" v-model="deptForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="上级部门：">
          <span v-if="!isRoot">{{parentDept}}</span>
          <el-select v-if="isRoot" v-model="selectDept" size="small" style="width:80%" filterable placeholder="请选择">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="isUpdate" label="创建人：">{{createPeople}}</el-form-item>
        <el-form-item v-show="isUpdate" label="创建时间：">{{createTime}}</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="success" @click="submitDept('deptForm')">保 存</el-button>
        <el-button size="small" type="danger" @click="cancleDept('deptForm')">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getDeptList,
  addDept,
  removeDept,
  findDept,
  getAllDept,
  updateDept } from '@/api/deptTable'
import TreeTable from '@/components/tree-table/index.vue'
export default {
  name: 'department',
  components: { TreeTable },
  data() {
    return {
      columns: [
        {
          text: '部门名称及操作',
          value: 'name'
        },
        {
          text: 'ID',
          value: 'id',
          width: 200
        },
        {
          text: '描述',
          value: 'remark'
        }
      ],
      isUpdate: false,
      isRoot: false,
      createPeople: '',
      createTime: '',
      selectDept: '',
      departments: [],
      deptData: [],
      choiceArr: [],
      deptVisible: false,
      title: '新增部门',
      parentDept: '',
      pid: null,
      removeIds: [],
      deptForm: {
        name: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        remark: [
          { required: false, message: '请填写部门描述', trigger: 'blur' }
        ]
      },
      deptSerData: '',
      hasAdd: false,
      hasDel: false,
      hasUpdate: false,
      addTitle: '新增',
      updateTitle: '修改',
      delTitle: '删除'
    }
  },
  mounted() {
    this.getDeptList()
    this.getAllDept()
    this.getJur()
  },
  methods: {
    getJur() {
      const self = this
      console.log(this.$store.userInfo,'getjur')
      self.$store.dispatch('Juage', self.$store.clickMenuId).then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            if (item.type == '3') {
              self.hasAdd = true
              self.addTitle = item.title
            }
            if (item.type == '5') {
              self.hasDel = true
              self.delTitle = item.title
            }
            if (item.type == '4') {
              self.hasUpdate = true
              self.updateTitle = item.title
            }
          })
        } else if (res.code !== '507') {
          self.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    getDeptList() {
      getDeptList().then(res => {
        if (res.code == '200') {
          this.deptData = res.data
          console.log(this.$store.userInfo,'userinfo')
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    getAllDept() {
      getAllDept().then(res => {
        if (res.code == '200') {
          this.departments = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    choice(val) {
    	console.log(val,'choice')
      this.choiceArr = val
      this.removeIds = []
      val.forEach(item => {
        this.removeIds.push(item.id)
      })
    },
    handleClose() {
      this.deptVisible = false
    },
    addLine() {
      const self = this
      if (self.choiceArr.length && self.choiceArr.length === 1) {
        self.title = '新增部门'
        self.deptVisible = true
        self.isUpdate = false
        self.parentDept = self.choiceArr[0].name
        self.pid = self.choiceArr[0].id
        self.isRoot = false
      }else if(self.choiceArr.length && self.choiceArr.length > 1){
      	self.$message({
          type: 'info',
          message: '请只选择一个节点作为上级部门增加部门！'
        })
      } else {
        this.$confirm('是否确认以根节点作为父节点增加部门?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.title = '新增部门'
	        self.deptVisible = true
	        self.isUpdate = false
	        self.parentDept = ''
	        self.pid = null
	        self.isRoot = true
        })
      }
    },
    submitDept(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          const para = {
            name: self.deptForm.name,
            remark: self.deptForm.remark
          }
          if (!self.isUpdate) {
            para.parentId = self.pid
            addDept(para).then(res => {
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getDeptList()
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          } else {
            self.departments.forEach(item => {
              if (item.name === self.selectDept) {
                para.parentId = item.id
              }
            })
            if(para.parentId == self.choiceArr[0].id){
            	self.$message({
			          type: 'info',
			          message: '上级部门不能选择自己！'
			        })
            	return false
            }
            para.id = self.choiceArr[0].id
            updateDept(para).then(res => {
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getDeptList()
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
            self.isRoot = false
          }
          self.deptVisible = false
          self.$refs[formName].resetFields()
        }
      })
    },
    cancleDept(formName) {
      this.deptVisible = false
      this.$refs[formName].resetFields()
    },
    removeLine() {
      const self = this
      if (self.choiceArr.length) {
        for (let i = 0; i < self.choiceArr.length; i++) {
          if (self.choiceArr[i].children.length) {
            self.$alert('您选择的部门包含下级部门，请先删除掉所有下级部门后再进行该操作！', '系统提示', {
              confirmButtonText: '确定',
              callback: action => {}
            })
            break
          } else {
            self.$confirm('确定要删除所选择的部门吗?', '信息确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              removeDept({ ids: self.removeIds.toString() }).then(res => {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getDeptList()
              })
            }).catch(() => {
              self.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
          }
        }
      } else {
        self.$message({
          type: 'info',
          message: '请先选择需要删除的部门！'
        })
      }
    },
    changeLine() {
      const self = this
      console.log(self.choiceArr[0],'dept')
      if (self.choiceArr.length && self.choiceArr.length === 1) {
        self.title = '修改部门'
        self.deptVisible = true
        self.isUpdate = true
        if (!self.choiceArr[0].children.length) {
          self.isRoot = true
        } else {
          self.isRoot = false
        }
        findDept({ id: self.choiceArr[0].id }).then(res => {
          if (res.code == '200') {
            self.deptForm.name = res.data.name
            self.deptForm.remark = res.data.remark
            self.parentDept = res.data.pname
            self.createPeople = res.data.createUserName
            self.selectDept = res.data.pname
            self.createTime = res.data.createTime.substring(0, 10)
          }
        })
      } else {
        self.$message({
          type: 'info',
          message: '请只选择一个需要修改的部门！'
        })
      }
    },
    findLine() {
      const para = { keywords: this.deptSerData }
      getDeptList(para).then(res => {
        if (res.code == '200') {
          this.deptData = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.btn-group{
  margin-bottom: 15px;
}
</style>

